package com.sjm.bookshop.service.client;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sjm.bookshop.dao.CartMapper;
import com.sjm.bookshop.dao.ClientDao;
import com.sjm.bookshop.dao.SlideDao;
import com.sjm.bookshop.entity.*;
import com.sjm.bookshop.utils.orderIdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class ClientService {
    @Autowired
    private SlideDao slideDao;

    @Autowired
    private ClientDao clientDao;

    @Autowired
    private CartMapper cartMapper;

    /**
     * 轮播
     *
     * @param status
     * @return List
     */
    public List<Slide> get(int status) {
        return slideDao.SlideList(status);
    }


    /**
     * 图书列表
     *
     * @param bookstatus
     * @return
     */
    public List<BookS> getBooks(int bookstatus) {
        return clientDao.bookList(bookstatus);
    }

    /**
     * 推荐图书列表
     *
     * @param recommend
     * @param bookstatus
     * @return
     */
    public List<BookS> getbookByRecommend(int recommend, int bookstatus) {
        return clientDao.getBooks(recommend, bookstatus);
    }

    /**
     * 图书详情
     *
     * @param bookId
     * @param bookstatus
     * @return
     */
    public BookS getDetail(int bookId, int bookstatus) {
        return clientDao.getById(bookId, bookstatus);
    }

    /**
     * 更多推荐
     * @return
     */
    public List<BookS> getMoreRecommend(){
        return clientDao.getRecommend();
    }
    public List<BookS> getMoreBookList(){
        return clientDao.getMoreList();
    }
    /**
     * 相关推荐
     *
     * @param type
     * @param bookstatus
     * @return
     */
    public List<BookS> relative(int type, int bookstatus) {
        return clientDao.getRelative(type, bookstatus);
    }

    /**
     * 添加购物车
     *
     * @param cart
     * @return
     */
    public int add(Cart cart) {
//        mybatis-plus的条件构造器设置查询的条件
        QueryWrapper<Cart> wrapper = new QueryWrapper<Cart>();
        wrapper.eq("u_id", cart.getU_id())
                .eq("b_id", cart.getB_id());
        List<Cart> selectList = cartMapper.selectList(wrapper);
        if (selectList.size() == 1) {
//            如果重复添加则对原来的信息进行修改
            cart.setAdd_time(new Date());
            return cartMapper.update(cart);
        } else {
//            如果不重复，则新加一条记录
            cart.setAdd_time(new Date());
            return cartMapper.insert(cart);
        }
    }

    /**
     * 查询购物车
     *
     * @param u_id
     * @return
     */
    public List<UCart> getCart(int u_id) {
        return cartMapper.getCartByUserId(u_id);
    }

    /**
     * 更新购物车
     *
     * @param cart
     * @return
     */
    public int update(Cart cart) {
        return cartMapper.update(cart);
    }

    /**
     * 删除购物车记录
     *
     * @param u_Id
     * @param b_Id
     * @return
     */
    public int delete(int u_Id, int b_Id) {
        QueryWrapper<Cart> wrapper = new QueryWrapper<Cart>();
        wrapper.eq("u_id", u_Id)
                .eq("b_id", b_Id);
        return cartMapper.delete(wrapper);
    }


    /**
     * 批量删除购物车记录
     *
     * @param list
     * @return
     */
    public int deleteBatch(List<Integer> list) {
        return cartMapper.deleteBatchById(list);
    }

    /**
     * 获取用户地址列表
     *
     * @param id
     * @return
     */
    public List<Address> getAddress(Integer id) {
        return clientDao.getUserAddressById(id);
    }

    /**
     * 根据id删除地址
     *
     * @param id
     * @return
     */
    public int del(int id) {
        return clientDao.deleteAddress(id);
    }

    /**
     * 更新地址
     *
     * @param address
     * @return
     */
    public int updateAddress(Address address) {
        int res = 0;
        if (address.getIsDefault() == 1) {

            if (clientDao.updateIsDefault(0) >= 0)
                res = clientDao.updateAddress(address);
        } else {
            res = clientDao.updateAddress(address);
        }
        return res;
    }

    /**
     * 新增地址
     *
     * @param address
     * @return
     */
    public int addAddress(Address address) {
        int result = 0;
        if (address.getIsDefault() == 1) {
            if (clientDao.updateIsDefault(0) >= 0)
                result = clientDao.addOneAddress(address);
        } else {
            result = clientDao.addOneAddress(address);
        }
        return result;
    }

    /**
     * 添加购物车，包括order表的记录、order_detail表的记录，添加成功后根据cartId删除购物车的记录
     *
     * @param map
     * @return
     * @throws ParseException
     */
    public int addOrder(Map<String, Object> map) throws ParseException {
        Object orderObject = JSONArray.toJSON(map.get("goodList"));
        String orderString = orderObject.toString();
        List<Map<String, Object>> lists = (List<Map<String, Object>>) JSONObject.parse(orderString);
//         转换成对应的时间格式，如果stringDate中没有‘,’号，格式转换中也不要加，保持一致
//        Object paytime = JSONArray.toJSON(map.get("paytime"));
//        String timeString = paytime.toString();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddHHmmss", Locale.ENGLISH);
//        Date date1 = sdf.parse(timeString);

//         生成订单号，订单生成时间
        String orderID = orderIdUtil.getLocalTrmSeqNum();
        Date date = new Date();

        // 为添加订单的对象设置值
        Orders order = new Orders();
        order.setUId((Integer) map.get("uid"));
        order.setOrderFId(orderID);
        order.setAddressId((Integer) map.get("addressId"));
        order.setAmountMoney((Integer) map.get("amountMoney"));
        order.setOrderStatus(1);
        order.setPaytype((String) map.get("paytype"));
        order.setCreatedtime(date);


        // 生成每一条订单详情，并获取cartId，进行批量删除
        List<OrderDetail> orderDetails = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        for (Map<String, Object> o : lists) {
            OrderDetail orderDetail = new OrderDetail();
            int goodId = Integer.parseInt(o.get("goodId").toString());
            int countNum = Integer.parseInt(o.get("countNum").toString());
            int price = Integer.parseInt(o.get("price").toString());
            list.add(Integer.parseInt(o.get("cartId").toString()));
            orderDetail.setGoodId(goodId);
            orderDetail.setPrice(price);
            orderDetail.setCountNum(countNum);
            orderDetail.setAddtime(date);
            orderDetail.setOrderId(orderID);
            orderDetails.add(orderDetail);
        }

        // 数据库操作，将goodId,countNum添加到map，根据key、value进行条件批量修改
        Map<Integer, Integer> integerMap = new HashMap<>();
        for (OrderDetail o : orderDetails) {
            integerMap.put(o.getGoodId(), o.getCountNum());
        }

        //添加到订单父表
       clientDao.addOrder(order);
        int i1 = clientDao.addOrderBacth(orderDetails);// 批量添加商品到订单子表
        if (i1 == orderDetails.size())
            cartMapper.deleteBatchById(list);
        int i2 = clientDao.matchByBookId(integerMap);// 修改库存
        if (i2 > 0) {
            return  1;
        } else {
            return  0;
        }

    }


    public int addOne(Map<String, Object> map) throws ParseException {
        // 生成订单号，订单生成时间
        String orderID = orderIdUtil.getLocalTrmSeqNum();
        Date date = new Date();
        // 为添加订单的对象设置值
        Orders order = new Orders();
        order.setUId((Integer) map.get("uid"));
        order.setOrderFId(orderID);
        order.setAddressId(Integer.parseInt(map.get("addressId").toString()));
        order.setAmountMoney(Integer.parseInt(map.get("amountMoney").toString()));
        order.setOrderStatus(1);
        order.setPaytype((String) map.get("paytype"));
        order.setCreatedtime(date);
        System.out.println(order);
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(orderID);
        orderDetail.setGoodId(Integer.parseInt(map.get("goodId").toString()));
        orderDetail.setPrice(Integer.parseInt(map.get("price").toString()));
        orderDetail.setCountNum(Integer.parseInt(map.get("countNum").toString()));
        orderDetail.setAddtime(new Date());
        Map<Integer, Integer> integerMap = new HashMap<>();
        integerMap.put(orderDetail.getGoodId(),orderDetail.getCountNum());
        //添加到订单父表
        int i = clientDao.addOrder(order);
        if(i > 0){
            clientDao.addOneOrder(orderDetail);
            clientDao.matchByBookId(integerMap);// 修改库存
        }
        return 1;
    }

    public List<Book> searchBook(String keyword) {
        return clientDao.getBookBySearch(keyword);
    }
}
